﻿using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using HYHY_Core.Enums;
using HYHY_Core.Tool.Token;
using HYHY_Core.Tool.Tool;
using HYQY_App.Admin_System.Interface;
using HYQY_Core.Entities.Advertising;
using HYQY_Core.Entities.Utils;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static HYQY_App.Admin_System.Dtos.AdvertisingAdminDto;

namespace HYQY_App.Admin_System.Service
{
    /// <summary>
    /// 广告管理
    /// </summary>
    [ApiDescriptionSettings(ApiGroupEnumsCode.Advertising, Name = "Advertising")]
    public class AdvertisingAdminService : IDynamicApiController, ITransient
    {
        /// <summary>
        /// sql
        /// </summary>
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 构造函数
        /// </summary>
        public AdvertisingAdminService(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 获取广告类型
        /// </summary>
        /// <returns></returns>
        public async Task<SelectAdvertisingTypeResp> SelectAdvertisingType()
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            var list = await _db.Queryable<AdvertisingType>()
                .Select(t1 => new SelectAdvertisingTypeOutput
                {
                    Id = t1.Id,
                    Type = t1.Type,
                }).ToListAsync();

            return new SelectAdvertisingTypeResp { List = list, Message = "请求成功", StatusCode = 200 };
        }

        /// <summary>
        /// 广告管理列表
        /// </summary>
        /// <returns></returns>
        public async Task<SelectAdvertisingListResp> SelectAdvertisingList(SelectAdvertisingListInput input)
        {

            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");
            // 去掉前后空格
            ToolHelper.TrimStrings(input);

            RefAsync<int> total = 0;
            var list = await _db.Queryable<Advertising>()
                .LeftJoin<AdvertisingType>((t1, t2) => t1.Type == t2.Id)
                .WhereIF(input.Type.HasValue, (t1, t2) => t1.Type == input.Type)
                .WhereIF(input.IsEnable.HasValue, (t1, t2) => t1.IsEnable == input.IsEnable)
                .Select((t1, t2) => new SelectAdvertisingListOutput
                {
                    Aid = t1.Aid,
                    ShowLocation = t1.ShowLocation,
                    Path = t1.Path,
                    IsEnable = t1.IsEnable,
                    Type = t2.Type,
                    Title = t1.Title,
                    Id = t2.Id,
                    BeginTime = t1.BeginTime,
                    EndTime = t1.EndTime,
                }).ToPageListAsync(input.Page, input.PageSize, total);

            return new SelectAdvertisingListResp { List = list, Message = "请求成功", StatusCode = 200, Total = total };
        }

        /// <summary>
        /// 设置广告状态
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseStatus> SetAdStatus(SetAdStatusInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");
            // 去掉前后空格
            ToolHelper.TrimStrings(input);

            if (string.IsNullOrWhiteSpace(input.Aid) || !input.IsEnable.HasValue)
            {
                throw Oops.Bah("请求失败=>【SetAdStatus】");
            }

            var ad = await _db.Queryable<Advertising>()
                .FirstAsync(it => it.Aid == input.Aid) ?? throw Oops.Bah("该广告不存在");

            ad.IsEnable = (bool)input.IsEnable;

            int count = await _db.Updateable(ad)
                .WhereColumns(it => it.Aid)
                .UpdateColumns(it => it.IsEnable).ExecuteCommandAsync();
            if (count < 1) { throw Oops.Bah("设置失败"); }

            return new ResponseStatus { StatusCode = 200, Message = "设置成功" };
        }

        /// <summary>
        /// 设置广告
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseStatus> SetAdvertising(AddAdvertisingInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");
            // 去掉前后空格
            ToolHelper.TrimStrings(input);

            if (string.IsNullOrWhiteSpace(input.Title)) throw Oops.Bah("广告标题不能为空");
            if (!input.Type.HasValue) throw Oops.Bah("请选择广告类型");
            if (string.IsNullOrWhiteSpace(input.ShowLocation)) throw Oops.Bah("请输入广告展示位置");
            if (!input.BeginTime.HasValue) throw Oops.Bah("请输入广告展示开始时间");
            if (!input.EndTime.HasValue) throw Oops.Bah("请输入广告展示结束时间");
            if (string.IsNullOrWhiteSpace(input.Path)) throw Oops.Bah("广告图片不能为空");

            string aid = Guid.NewGuid().ToString("N");
            var count = await _db.Insertable(new Advertising
            {
                Aid = aid,
                Path = input.Path,
                IsEnable = input.IsEnable,
                BeginTime = input.BeginTime.Value,
                EndTime = input.EndTime.Value,
                ShowLocation = input.ShowLocation,
                Title = input.Title,
                Type = input.Type.Value,
                CreateMan = user.UserName,
                CreateTime = DateTime.Now,
            }).ExecuteCommandAsync();

            if (count < 1)
            {
                throw Oops.Bah("设置失败=>【SetAdvertising】");
            }
            return new ResponseStatus { Message = "广告设置成功", StatusCode = 200 };
        }

        /// <summary>
        /// 编辑广告
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseStatus> UpdateAdvertising(UpdateAdvertisingInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");
            // 去掉前后空格
            ToolHelper.TrimStrings(input);

            if (string.IsNullOrWhiteSpace(input.Title)) throw Oops.Bah("广告标题不能为空");
            if (!input.Type.HasValue) throw Oops.Bah("请选择广告类型");
            if (string.IsNullOrWhiteSpace(input.ShowLocation)) throw Oops.Bah("请输入广告展示位置");
            if (!input.BeginTime.HasValue) throw Oops.Bah("请输入广告展示开始时间");
            if (!input.EndTime.HasValue) throw Oops.Bah("请输入广告展示结束时间");
            if (string.IsNullOrWhiteSpace(input.Path)) throw Oops.Bah("广告图片不能为空");

            var ad = await _db.Queryable<Advertising>()
                .FirstAsync(it => it.Aid == input.Aid) ?? throw Oops.Bah("广告不存在=>【UpdateAdvertising】");

            ad.Title = input.Title;
            ad.ShowLocation = input.ShowLocation;
            ad.BeginTime = (DateTime)input.BeginTime;
            ad.EndTime = (DateTime)input.EndTime;
            ad.Path = input.Path;
            ad.Type = (int)input.Type;
            ad.IsEnable = input.IsEnable;
            ad.UpdateMan = user.UserName;
            ad.UpdateTime = DateTime.Now;

            int count = await _db.Updateable(ad)
                .WhereColumns(it => it.Aid)
                .UpdateColumns(it => new
                {
                    it.Title,
                    it.ShowLocation,
                    it.BeginTime,
                    it.EndTime,
                    it.Path,
                    it.Type,
                    it.IsEnable,
                    it.UpdateMan,
                    it.UpdateTime
                }).ExecuteCommandAsync();

            if (count < 1) { throw Oops.Bah("广告修改失败=>【UpdateAdvertising】"); }

            return new ResponseStatus { Message = "广告编辑成功", StatusCode = 200 };
        }

        public async Task<ResponseStatus> DeleteAdvertising(DeleteAdvertisingInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");
            // 去掉前后空格
            ToolHelper.TrimStrings(input);

            var ad = await _db.Queryable<Advertising>()
               .FirstAsync(it => it.Aid == input.Aid) ?? throw Oops.Bah("广告不存在=>【DeleteAdvertising】");

            ad.IsDelete = true;
            int count = await _db.Updateable(ad)
                .WhereColumns(it => it.Aid)
                .UpdateColumns(it => it.IsDelete).ExecuteCommandAsync();

            if (count < 1) { throw Oops.Bah("广告删除失败=>【DeleteAdvertising】"); }

            return new ResponseStatus { Message = "广告删除成功", StatusCode = 200 };
        }
    }
}
